package hongcaosp.app.android.redpacket;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;

import com.alibaba.fastjson.JSON;

import java.net.SocketTimeoutException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import okio.ByteString;
import xlj.lib.android.base.component.ActivityStack;
import xlj.lib.android.base.utils.TaskPool;

public class RedPacketService extends Service {

    public static final int MSGTYPE_START = 1;
    public static final int MSGTYPE_CATCH_PACKET = 2;

    public static final int MSGTYPE_STOP = 3;

    public static WebSocket redSocket;
    private String url;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent == null) {
            return super.onStartCommand(intent, flags, startId);
        }
        int type = intent.getIntExtra("msgType", MSGTYPE_START);
        if (type == MSGTYPE_START) {
            String newUrl = intent.getStringExtra("url");
            if (newUrl != null && !newUrl.equals(url) || redSocket == null) {
                url = newUrl;
                try {
                    startWebSocket();
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.e("RedPacketService", e.getMessage());
                }
            }
        } else if (type == MSGTYPE_CATCH_PACKET) {
            sendCatchPacket();
        } else if (type == MSGTYPE_STOP) {
            if (redSocket != null) {
                redSocket.cancel();
                redSocket = null;
            }
        }

        return super.onStartCommand(intent, flags, startId);
    }

    private void sendCatchPacket() {
        if (redSocket != null) {
            Map<String, Object> map = new HashMap<>();
            map.put("msgType", 1);
            map.put("serviceType", "rp");
            if (redSocket.send(JSON.toJSONString(map))) {
                if (redPacketDialog != null && redPacketDialog.isShowing()) {
                    redPacketDialog.showProgress();
                }
            }
        }
    }

    private void startWebSocket() {
        if (redSocket != null) {
            redSocket.cancel();
        }
        OkHttpClient mOkHttpClient = new OkHttpClient.Builder()
                .readTimeout(15, TimeUnit.SECONDS)//设置读取超时时间
                .writeTimeout(15, TimeUnit.SECONDS)//设置写的超时时间
                .connectTimeout(15, TimeUnit.SECONDS)//设置连接超时时间
                .build();


        Request request = new Request.Builder().url(url).build();
        EchoWebSocketListener socketListener = new EchoWebSocketListener();
        mOkHttpClient.newWebSocket(request, socketListener);
        mOkHttpClient.dispatcher().executorService().shutdown();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    RedPacketDialog redPacketDialog;

    private void showRedPacketDialog() {
        if (ActivityStack.topActivity() != null) {
            if (redPacketDialog != null && redPacketDialog.isShowing()) {
                redPacketDialog.dismiss();
            }
            redPacketDialog = new RedPacketDialog(ActivityStack.topActivity());
            redPacketDialog.show();
        }
    }

    private final class EchoWebSocketListener extends WebSocketListener {

        @Override
        public void onOpen(WebSocket webSocket, Response response) {
            super.onOpen(webSocket, response);
            redSocket = webSocket;

            Log.i("RedPacketService", "onOpen");

        }

        @Override
        public void onMessage(WebSocket webSocket, ByteString bytes) {
            super.onMessage(webSocket, bytes);
            Log.i("RedPacketService", "onMessage");
        }

        @Override
        public void onMessage(WebSocket webSocket, final String text) {
            super.onMessage(webSocket, text);
            TaskPool.myPool().postTaskOnMain(new Runnable() {
                @Override
                public void run() {
                    Log.i("RedPacketService", "消息：" + text);
                    try {
                        RedPacket redPacket = JSON.parseObject(text, RedPacket.class);
                        if (redPacket.getMsgType() == 0) {
                            //显示红包界面
                            showRedPacketDialog();
                        } else if (redPacket.getMsgType() == 1) {
                            //显示红包结果页面
                            RedPacketOpenDialog redPacketOpenDialog = new RedPacketOpenDialog(ActivityStack.topActivity());
                            redPacketOpenDialog.setText(redPacket.getContent() + "元",redPacket.getMsgType());
                            redPacketOpenDialog.show();

//                            if (redPacketDialog != null) {
                                redPacketDialog.dismiss();
//                            }
                        } else if (redPacket.getMsgType() == -1) {
                            //异常消息
                            RedPacketOpenDialog redPacketOpenDialog = new RedPacketOpenDialog(ActivityStack.topActivity());
                            redPacketOpenDialog.setText(redPacket.getContent(),redPacket.getMsgType());
                            redPacketOpenDialog.setDimissDetail(true);
                            redPacketOpenDialog.show();

//                            if (redPacketDialog != null) {
                                redPacketDialog.dismiss();
//                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });

        }

        @Override
        public void onClosed(WebSocket webSocket, int code, String reason) {
            super.onClosed(webSocket, code, reason);
            Log.i("RedPacketService", "onClosed");
        }

        @Override
        public void onClosing(WebSocket webSocket, int code, String reason) {
            super.onClosing(webSocket, code, reason);
            Log.i("RedPacketService", "onClosing");
        }

        @Override
        public void onFailure(WebSocket webSocket, Throwable t, Response response) {
            super.onFailure(webSocket, t, response);
            Log.i("RedPacketService", "onFailure");
            if (t != null && t.getMessage() == null) {
                //这里粗暴点，不搞链接失败次数 也不管是否有网
                startWebSocket();
                return;
            }
            redSocket = null;
        }
    }

}
